package com.lin.mr.maizilaundry.fragmentcloth;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lin.mr.maizilaundry.R;
import com.lin.mr.maizilaundry.activity.HomeActivity;
import com.lin.mr.maizilaundry.entity.Laundry;
import com.lin.mr.maizilaundry.myadapter.VolleyAdapter;
import com.lin.mr.maizilaundry.myapplication.MyApplication;
import com.lin.mr.maizilaundry.utils.CountEvent;
import com.lin.mr.maizilaundry.utils.ShareUtils;
import com.lin.mr.maizilaundry.utils.TimeUtils;
import com.lin.mr.maizilaundry.utils.VolleyUtils;
import com.lin.mr.maizilaundry.utils.WashInfoJean;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 *
 */
public class FragmentSpring extends Fragment implements View.OnClickListener {
    //    private View view;
    private GridView gridView;
    private ProgressBar pb;
    private PopupWindow popupWindow;
    private ImageView iv_picture;
    private TextView tv_name;
    private TextView tv_price;
    private TextView tv_sum;
    private ImageButton btn_minus;
    private ImageButton btn_plus;
    private Button btn_sure;
    private Laundry laundry;
    private ImageView iv_float;
    int currentPosition;//选中的的GridView的项的下标号
    int previousSum;
    int currentSum;
    String currentTime;//下单时的时间

    private List<WashInfoJean.WashInfoBean> washList;

    private String URL = "http://cloud.bmob.cn/d9f6840be6bb07cf/wash_spring";
    private int startX;
    private int startY;
    private int endX;
    private int endY;
    private int left;
    private int right;
    private int top;
    private int bottom;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.e("悬浮", "onCreateView");
        View view = inflater.inflate(R.layout.fragment_cloth, null);
//        this.view = view;
        iv_float = (ImageView) view.findViewById(R.id.iv_float);
        gridView = (GridView) view.findViewById(R.id.gridView_cloth);
        gridView.setVisibility(View.INVISIBLE);//在GridView加载数据之前将其设为不可见
        pb = (ProgressBar) view.findViewById(R.id.progressBar);
//        floatLocation();
//        floatImage();

        //悬浮图标
        if(MyApplication.laundries.size() != 0){
            iv_float.setImageResource(R.mipmap.laundry_dot);
        }else {
            iv_float.setImageResource(R.mipmap.laundry);
        }
        //点击悬浮按钮跳转到洗衣篮页面（偶尔会失灵）
        iv_float.setOnClickListener(new View.OnClickListener() {
//            long[] mHits = new long[1];// 数组长度表示要点击的次数

            @Override
            public void onClick(View v) {
                HomeActivity.homeIndex(1);
                getActivity().finish();
                HomeActivity.jumpToPage(true);
//                Log.e("tag", "已经点击");
////                双击时间的简便写法，参考Android源码
//                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
//                mHits[mHits.length - 1] = SystemClock.uptimeMillis();// 开机后开始计算的时间
//                if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
//                    HomeActivity.homeIndex(1);
//                    getActivity().finish();
//                    HomeActivity.jumpToPage(true);
//                }
            }
        });
        return view;
    }


    /**
     * 悬浮按钮
     * 1.洗衣篮为空和不为空时的图标切换
     * 2.拖拽动画
     */
    private void floatImage() {
//        floatLocation();

        //获取屏幕宽高
        DisplayMetrics dm = getResources().getDisplayMetrics();
        final int screenWidth = dm.widthPixels;
        final int screenHeight = dm.heightPixels;

        //悬浮按钮
        if (MyApplication.laundries.size() != 0) {
            iv_float.setImageResource(R.mipmap.laundry_dot);
        } else {
            iv_float.setImageResource(R.mipmap.laundry);
        }


        /**
         * 悬浮按钮的拖拽效果
         */
        iv_float.setOnTouchListener(new View.OnTouchListener() {
            // 获取屏幕宽高

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //起始坐标
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        endX = (int) event.getRawX();
                        endY = (int) event.getRawY();
                        //移动的偏移量
                        int dx = endX - startX;
                        int dy = endY - startY;
                        //更新移动后的距离屏幕上下左右的距离
                        left = iv_float.getLeft() + dx;
                        right = iv_float.getRight() + dx;
                        top = iv_float.getTop() + dy;
                        bottom = iv_float.getBottom() + dy;
                        //防止悬浮按钮被拖出屏幕边界
                        if (left < 0 || right > screenWidth || top < 0 || bottom > screenHeight - 390) {

                            break;
                        }
                        int b = screenHeight - 200;
                        Log.e("悬浮", "bottom:" + bottom + "," + "screenHeight-200:" + b);
                        //更新界面
                        iv_float.layout(left, top, right, bottom);
                        // 重新初始化起点坐标
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        ShareUtils.putLeft(MyApplication.getContext(), iv_float.getLeft());
                        ShareUtils.putTop(MyApplication.getContext(), iv_float.getTop());
                        Log.e("悬浮", "左:" + iv_float.getLeft() + "," + "上:" + iv_float.getTop());
                        break;
                }
                return false;
            }
        });


    }

    //更新悬浮按钮的位置
    public void floatLocation() {
        //让悬浮按钮出现在用户上次拖拽完的位置
        int lastLeft = ShareUtils.getLeft(MyApplication.getContext());
        int lastTop = ShareUtils.getTop(MyApplication.getContext());
//        WindowManager.LayoutParams params = new WindowManager.LayoutParams();

        if (lastLeft != 0 && lastTop != 0) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) iv_float
                    .getLayoutParams();// 获取布局对象

            layoutParams.leftMargin = lastLeft;
            layoutParams.topMargin = lastTop;
            iv_float.setLayoutParams(layoutParams);
            Log.e("悬浮", "lastLeft:" + lastLeft + "," + "lastTop:" + lastTop);
        }
        iv_float.setVisibility(View.VISIBLE);
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            VolleyUtils.requestByGet(URL, "FragmentSpring", new VolleyUtils.CallBack() {
                @Override
                public void returnData(Object result) {
                    if (result != null) {
                        Gson gson = new Gson();
                        WashInfoJean washJean = gson.fromJson((String) result, WashInfoJean.class);
                        washList = new ArrayList<WashInfoJean.WashInfoBean>();
                        washList = washJean.getWashInfo();
                        gridView.setAdapter(new VolleyAdapter(getActivity(), washList));
                        initPopupWindow();
                        //延时2s显示GridView
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                try {
                                    Thread.sleep(1000);
                                    handler.sendEmptyMessage(0);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                /*
                                    使用runOnUiThread的getActivity容易报空指针，后改用handler
                                 */
                            }
                        }.start();

                        //gridView的点击事件
                        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                currentPosition = position;
                                showPopupWindow(position);
                                if (popupWindow != null && popupWindow.isShowing()) {
                                    popupWindow.dismiss();
                                } else {
                                    tv_sum.setText("1");//将PopupWindow中的衣服件数初始化为1
                                    popupWindow.showAtLocation(gridView, Gravity.BOTTOM, 0, 0);
                                }
                            }
                        });
                    } else {
                        Toast.makeText(getActivity(), "请检查网络!", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pb.setVisibility(View.INVISIBLE);
            gridView.setVisibility(View.VISIBLE);
//            floatLocation();
        }
    };


    public void initPopupWindow() {
        View view = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.popupwindow_item, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        //设置PopupWindow的属性
        ColorDrawable dw = new ColorDrawable(0xb0000000);//设置背景色
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.getBackground().setAlpha(50);//设置透明度
        popupWindow.setOutsideTouchable(true);//设置可以点击
        popupWindow.setFocusable(true);//使popupwindow获得焦点
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取控件
        iv_picture = (ImageView) view.findViewById(R.id.pop_bag_image);
        tv_sum = (TextView) view.findViewById(R.id.pop_bag_sum);
        tv_name = (TextView) view.findViewById(R.id.pop_bag_text);
        tv_price = (TextView) view.findViewById(R.id.pop_bag_price);
        btn_minus = (ImageButton) view.findViewById(R.id.pop_bag_minus);
        btn_plus = (ImageButton) view.findViewById(R.id.pop_bag_plus);
        btn_sure = (Button) view.findViewById(R.id.btn_pop_sure);

        btn_minus.setOnClickListener(this);
        btn_plus.setOnClickListener(this);
        btn_sure.setOnClickListener(this);
    }

    private void showPopupWindow(int position) {
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
                getActivity()).threadPoolSize(5).build();
        ImageLoader.getInstance().init(configuration);
        //ImageLoader配置
        DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.ic)
                .displayer(new FadeInBitmapDisplayer(100)).displayer(new RoundedBitmapDisplayer(50)).build();

        ImageLoader.getInstance().displayImage(washList.get(position).getWashHead(), iv_picture, options);
        tv_price.setText(washList.get(position).getAmount());
        tv_name.setText(washList.get(position).getWashName());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pop_bag_minus:
                getPreviousSum();
                if (previousSum > 1) {
                    currentSum = previousSum - 1;
                    tv_sum.setText(currentSum + "");
                }
                break;
            case R.id.pop_bag_plus:
                getPreviousSum();
                currentSum = previousSum + 1;
                tv_sum.setText(currentSum + "");
                break;
            case R.id.btn_pop_sure:
                if (popupWindow != null && popupWindow.isShowing()) {
                    Boolean isRepeat = isRepeatedData();
                    String name = (String) tv_name.getText();
                    if (isRepeat) { //判断是否之前是否有添加进洗衣篮的衣服
                        for (int i = 0; i < MyApplication.laundries.size(); i++) {
                            laundry = MyApplication.laundries.get(currentPosition);
                            //判断洗衣篮中的衣服是否跟用户当前选择的衣服相同
                            if (name.equals(laundry.getPictureName())) {
                                //获取洗衣篮中的件数
                                String string1 = laundry.getAmount();
                                int amount1 = Integer.parseInt(string1);
                                //获取用户当前添加的件数
                                String string2 = (String) tv_sum.getText();
                                int amount2 = Integer.parseInt(string2);
                                //将之前添加的件数和当前添加的件数相加
                                laundry.setAmount(amount1 + amount2 + "");
                                break;
                            }
                        }
                    } else {
                        Laundry laundry = new Laundry();
                        laundry.setPicture(washList.get(currentPosition).getWashHead());//图片
                        laundry.setValue((String) tv_price.getText());//价格
                        laundry.setAmount((String) tv_sum.getText());//数量
                        laundry.setPictureName((String) tv_name.getText());
                        //获取下单时的时间
                        currentTime = TimeUtils.getTime(System.currentTimeMillis());
                        laundry.setTime(currentTime);
                        MyApplication.laundries.add(laundry);
                    }
                    Toast.makeText(getActivity(), "已加入洗衣篮(∩_∩)", Toast.LENGTH_SHORT).show();
                    popupWindow.dismiss();
                    //悬浮图标
                    if (MyApplication.laundries.size() != 0) {
                        iv_float.setImageResource(R.mipmap.laundry_dot);
                    } else {
                        iv_float.setImageResource(R.mipmap.laundry);
                    }
                    EventBus.getDefault().post(new CountEvent(4));

                }
                break;
        }

    }

    //获取PopupWindow中的件数
    public void getPreviousSum() {
        String text = tv_sum.getText().toString();
        previousSum = Integer.parseInt(text);
    }

    /**
     * 判断是否有重复数据
     *
     * @return
     */
    private Boolean isRepeatedData() {
        String tv_nameText = (String) tv_sum.getText();
        for (int i = 0; i < MyApplication.laundries.size(); i++) {
            laundry = MyApplication.laundries.get(i);
            if (tv_nameText.equals(laundry.getPictureName())) {
                return true;
            }
        }
        return false;
    }
}
